<template>
	<view class="form-container">
	
		<!-- 表单内容 -->
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-content">
				<view class="form-item">
					<text class="form-label">单号：</text>
					<input class="form-input" v-model="form.orderNo" placeholder="请输入单号" />
				</view>
				<view class="form-item">
					<text class="form-label">关联塘头单：</text>
					<input class="form-input" v-model="form.linkedOrder" placeholder="请输入关联塘头单" />
				</view>
				<view class="form-item">
					<text class="form-label">批次号：</text>
					<input class="form-input" v-model="form.batchNo" placeholder="请输入批次号" />
				</view>
				<view class="form-item">
					<text class="form-label">供货鱼种：</text>
					<input class="form-input" v-model="form.fishType" placeholder="请输入供货鱼种" />
				</view>
				<view class="form-item">
					<text class="form-label">工厂：</text>
					<input class="form-input" v-model="form.supplier" placeholder="请输入工厂" />

				</view>
				<view class="form-item">
					<text class="form-tip red-tip" v-if="showSupplierTip">支持多个</text>
				</view>
				<view class="form-item">
					<text class="form-label">运输车辆：</text>
					<input class="form-input" v-model="form.carNo" placeholder="支持多个，用逗号分隔" />
				</view>
				<view class="form-item">
					<text class="form-label">联系人：</text>
					<input class="form-input" v-model="form.contact" placeholder="请输入联系人" />
				</view>
				<view class="form-item">
					<text class="form-label">联系人电话号码：</text>
					<input class="form-input" v-model="form.contactPhone" placeholder="请输入联系人电话" />
				</view>
				<view class="form-item">
					<text class="form-label">日期：</text>
					<picker mode="date" :value="form.date" @change="onDateChange">
						<view class="picker-input">{{ form.date || '请选择日期' }}</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="form-label">时间：</text>
					<picker mode="time" :value="form.time" @change="onTimeChange">
						<view class="picker-input">{{ form.time || '请选择时间' }}</view>
					</picker>
				</view>
				<view class="form-item" v-if="location">
					<text class="form-label">定位地址：</text>
					<text class="location-text">{{ location }}</text>
				</view>
				<view class="form-item photos">
					<!-- <text class="form-label">现场照片</text> -->
					<view class="photo-card">
						<view class="photo-header">
							<text class="photo-title">现场环境凭证</text>
							<text class="photo-desc">需上传 {{ minScenePhotos }}-{{ maxScenePhotos }} 张现场照片</text>
						</view>
						<view class="photo-grid">
							<view class="photo-item" v-for="(photo, index) in scenePhotos" :key="photo">
								<image class="photo-image" :src="photo" mode="aspectFill" @click="previewPhoto('scene', index)" />
								<view class="photo-delete" @click.stop="removePhoto('scene', index)">
									<text class="delete-icon">×</text>
								</view>
							</view>
							<view class="photo-item upload" v-if="scenePhotos.length < maxScenePhotos" @click="choosePhotos('scene')">
								<view class="upload-icon">
									<text class="camera-icon">📷</text>
								</view>
								<text class="upload-text">添加照片</text>
								<text class="upload-sub">需{{ minScenePhotos }}-{{ maxScenePhotos }}张</text>
							</view>
						</view>
						<text class="photo-tip">已选 {{ scenePhotos.length }} 张</text>
					</view>
				</view>
				<!-- 单据照片部分已移除，移至汇总详情页面 -->
			</view>
		</scroll-view>
		
		<!-- 悬浮拍照按钮 -->
		<view class="photo-fab" @click="openPhotoManager">
			<text class="fab-icon">📷</text>
		</view>
		
		<button class="next-btn" :class="{ 'disabled': submitting }" :disabled="submitting" @click="nextStep">
			{{ submitting ? '提交中...' : '下一步' }}
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					orderNo: '',
					linkedOrder: '',
					batchNo: '',
					fishType: '',
					supplier: '',
					carNo: '',
					contact: '',
					contactPhone: '',
					date: '',
					time: ''
				},
				showSupplierTip: true,
				location: '',
				scenePhotos: [],
				minScenePhotos: 1,
				maxScenePhotos: 5,
				submitting: false
			}
		},
		onLoad() {
			this.ensureValidDateTime(true)
			this.restoreMediaData()
			this.getLocation()
		},
		onShow() {
			this.ensureValidDateTime()
		},
		methods: {
			/**
			 * 打开照片管理页面
			 */
			openPhotoManager() {
				uni.navigateTo({
					url: '/pages/home/gongchang/photo-manager'
				});
			},

			formatDate(now) {
				const y = now.getFullYear()
				const m = String(now.getMonth() + 1).padStart(2, '0')
				const d = String(now.getDate()).padStart(2, '0')
				return `${y}-${m}-${d}`
			},
			formatTime(now) {
				const hh = String(now.getHours()).padStart(2, '0')
				const mm = String(now.getMinutes()).padStart(2, '0')
				return `${hh}:${mm}`
			},
			ensureValidDateTime(force = false) {
				const now = new Date()
				const datePattern = /^\d{4}-\d{2}-\d{2}$/
				const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/
				if (force || !datePattern.test(this.form.date)) {
					this.form.date = this.formatDate(now)
				}
				if (force || !timePattern.test(this.form.time)) {
					this.form.time = this.formatTime(now)
				}
			},
			onDateChange(e) {
				this.form.date = e.detail.value
				this.ensureValidDateTime()
			},
			onTimeChange(e) {
				this.form.time = e.detail.value
				this.ensureValidDateTime()
			},
			getPhotoConfig(type) {
				const map = {
					scene: { key: 'scenePhotos', min: this.minScenePhotos, max: this.maxScenePhotos }
				}
				return map[type]
			},
			getPhotoList(type) {
				const config = this.getPhotoConfig(type)
				return this[config.key] || []
			},
			choosePhotos(type) {
				const config = this.getPhotoConfig(type)
				const targetList = this.getPhotoList(type)
				const remaining = config.max - targetList.length
				if (remaining <= 0) {
					uni.showToast({
						title: `最多上传${config.max}张照片`,
						icon: 'none'
					})
					return
				}
				uni.chooseImage({
					count: remaining,
					sizeType: ['compressed'],
					success: (res) => {
						const merged = [...targetList, ...res.tempFilePaths]
						this[config.key] = merged.slice(0, config.max)
					}
				})
			},
			previewPhoto(type, index) {
				const list = this.getPhotoList(type)
				if (!list.length) return
				uni.previewImage({
					current: list[index],
					urls: list
				})
			},
			removePhoto(type, index) {
				const config = this.getPhotoConfig(type)
				const list = [...this.getPhotoList(type)]
				uni.showModal({
					title: '提示',
					content: '确认删除该照片吗？',
					success: (res) => {
						if (res.confirm) {
							list.splice(index, 1)
							this[config.key] = list
						}
					}
				})
			},
			validatePhotos() {
				if (this.scenePhotos.length < this.minScenePhotos) {
					uni.showToast({
						title: `现场照片至少上传${this.minScenePhotos}张`,
						icon: 'none'
					})
					return false
				}
				return true
			},
			getLocation() {
				const that = this
				wx.getLocation({
					type: 'gcj02',
					success(res) {
						that.reverseGeocoder(res.latitude, res.longitude)
					},
					fail(err) {
						console.error('获取位置失败:', err)
					}
				})
			},
			reverseGeocoder(latitude, longitude) {
				const key = '2DCBZ-TQR6T-BNDX5-LVCAI-Z7PX2-WQFEB'
				wx.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					data: {
						location: `${latitude},${longitude}`,
						key,
						get_poi: 1
					},
					success: (res) => {
						if (res.data.status === 0) {
							this.location = res.data.result.address || ''
							uni.setStorageSync('factoryLocation', this.location)
						}
					},
					fail: (err) => {
						console.log('解析地址失败', err)
					}
				})
			},
			restoreMediaData() {
				const savedScene = uni.getStorageSync('factoryScenePhotos') || []
				const savedLocation = uni.getStorageSync('factoryLocation') || ''
				this.scenePhotos = Array.isArray(savedScene) ? savedScene : []
				if (savedLocation) {
					this.location = savedLocation
				}
			},
			nextStep() {
				if (!this.validatePhotos()) {
					return
				}
				uni.setStorageSync('factoryScenePhotos', this.scenePhotos)
				uni.setStorageSync('factoryLocation', this.location)
				uni.navigateTo({
					url: '/pages/home/gongchang/aggregate-detail'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.form-container {
		background: $bg-secondary;
		min-height: 100vh;
		position: relative;
	}

	/* 顶部装饰 */
	.header-decoration {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 200rpx;
		z-index: 1;
		overflow: hidden;
	}

	.wave-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, $secondary 0%, $accent 100%);
		border-radius: 0 0 30% 30%;
		transform: scale(1.1);
	}

	.floating-elements {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.element {
		position: absolute;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		animation: element-float 6s ease-in-out infinite;
	}

	.element-1 {
		width: 40rpx;
		height: 40rpx;
		top: 30%;
		left: 20%;
		animation-delay: 0s;
	}

	.element-2 {
		width: 60rpx;
		height: 60rpx;
		top: 60%;
		right: 25%;
		animation-delay: 3s;
	}

	@keyframes element-float {

		0%,
		100% {
			transform: translateY(0px) scale(1);
			opacity: 0.6;
		}

		50% {
			transform: translateY(-20rpx) scale(1.1);
			opacity: 1;
		}
	}

	/* 页面标题 */
	.page-header {
		position: relative;
		z-index: 2;
		padding: 40rpx 40rpx 30rpx 40rpx;
		background: transparent;
	}

	.header-content {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.page-title {
		display: block;
		font-size: 36rpx;
		font-weight: 700;
		color: $text-white;
		margin-bottom: 8rpx;
		text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
	}

	.page-subtitle {
		display: block;
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
		font-weight: 400;
	}

	.progress-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.progress-step {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.3);
		color: rgba(255, 255, 255, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $font-sm;
		font-weight: 600;
		transition: all 0.3s ease;
	}

	.progress-step.active {
		background: $text-white;
		color: $secondary;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
	}

	.progress-line {
		width: 60rpx;
		height: 2rpx;
		background: rgba(255, 255, 255, 0.3);
		margin: 0 16rpx;
	}

	.header-bar {
		display: flex;
		align-items: center;
		height: 80rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 10rpx;
	}

	.back-btn {
		font-size: 40rpx;
		color: #3b6ca8;
		margin-right: 20rpx;
		width: 60rpx;
		text-align: center;
		cursor: pointer;
	}

	.header-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	/* 表单滚动区域 */
	.form-scroll {
		flex: 1;
		width: 92%;
		/* 统一左右留白 */
		padding: 0 32rpx;
		/* 预留底部按钮空间，避免遮挡输入框 */
		padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
		position: relative;
		z-index: 2;
	}

	.form-content {
		background: $bg-primary;
		border-radius: $radius-lg;
		margin: 12rpx auto 28rpx;
		padding: 30rpx;
		max-width: 660rpx;
		box-shadow: $shadow-md;
		border: 1rpx solid $border-light;
	}

	/* 表单项目 */
	.form-item {
		margin-bottom: 32rpx;
		position: relative;
	}

	.form-label {
		display: block;
		font-size: $font-md;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: 12rpx;
		line-height: 1.4;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid $border-light;
		border-radius: $radius-md;
		padding: 0 20rpx;
		font-size: $font-md;
		color: $text-primary;
		background: $bg-primary;
		transition: all 0.3s ease;
		box-sizing: border-box;
	}

	.picker-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid $border-light;
		border-radius: $radius-md;
		padding: 0 20rpx;
		font-size: $font-md;
		color: $text-primary;
		background: $bg-primary;
		display: flex;
		align-items: center;
		box-sizing: border-box;
	}

	.form-input:focus {
		border-color: $secondary;
		box-shadow: 0 0 0 6rpx rgba(38, 198, 218, 0.1);
		outline: none;
	}

	.form-input::placeholder {
		color: $text-tertiary;
	}

	.location-text {
		display: block;
		font-size: 24rpx;
		color: $text-secondary;
		line-height: 1.6;
		word-break: break-all;
	}

	.photo-card {
		background: $bg-primary;
		border-radius: $radius-lg;
		border: 1rpx solid $border-light;
		box-shadow: $shadow-md;
		padding: 28rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.photo-header {
		display: flex;
		flex-direction: column;
		gap: 6rpx;
	}

	.photo-title {
		font-size: $font-lg;
		font-weight: 600;
		color: $text-primary;
	}

	.photo-desc {
		font-size: $font-sm;
		color: $text-secondary;
	}

	.photo-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
	}

	.photo-item {
		position: relative;
		border-radius: $radius-md;
		border: 2rpx solid $border-light;
		background: $bg-primary;
		box-shadow: $shadow-sm;
		overflow: hidden;
		aspect-ratio: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.photo-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.photo-delete {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.55);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-icon {
		font-size: 28rpx;
		color: $text-white;
		line-height: 1;
	}

	.photo-item.upload {
		border-style: dashed;
		border-color: rgba(30, 136, 229, 0.35);
		background: rgba(30, 136, 229, 0.05);
		flex-direction: column;
		gap: 10rpx;
	}

	.photo-item.upload:active {
		background: rgba(30, 136, 229, 0.12);
		border-color: $primary;
	}

	.upload-icon {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		background: rgba(30, 136, 229, 0.12);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.camera-icon {
		font-size: 36rpx;
	}

	.upload-text {
		font-size: $font-sm;
		color: $primary;
		font-weight: 600;
	}

	.upload-sub {
		font-size: 22rpx;
		color: $text-tertiary;
	}

	.photo-tip {
		font-size: 24rpx;
		color: $text-tertiary;
	}

	@media screen and (max-width: 600rpx) {
		.photo-grid {
			grid-template-columns: repeat(2, 1fr);
		}
	}

	.form-tip {
		position: absolute;
		right: 0;
		top: 50%;
		
		
		font-size: $font-sm;
		color: $text-tertiary;
		margin-left: auto;
		padding-right: 2rpx;
	}

	.red-tip {
		color: #e53935 !important;
		font-size: 22rpx;
	}

	/* 下一步按钮 */
	.next-btn {
		position: fixed;
		bottom: 30rpx;
		left: 50%;
		transform: translateX(-50%);
		width: calc(100% - 60rpx);
		max-width: 660rpx;
		height: 88rpx;
		background: linear-gradient(135deg, $primary 0%, $primary-light 100%);
		color: $text-white;
		border: none;
		border-radius: $radius-xl;
		font-size: $font-lg;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: $shadow-lg;
		transition: all 0.3s ease;
		z-index: 10;
	}

	// .next-btn:hover {
	// 	transform: translateY(-2rpx);
	// 	box-shadow: $shadow-xl;
	// }

	.next-btn:active {
		transform: translateX(-50%);
		box-shadow: $shadow-md;
	}

	.next-btn:disabled {
		background: $text-disabled;
		color: $text-white;
		transform: none;
		box-shadow: none;
		opacity: 0.6;
	}

	/* 悬浮拍照按钮 */
	.photo-fab {
		position: fixed;
		bottom: 140rpx;
		right: 32rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, $primary 0%, $primary-light 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 24rpx rgba(30, 136, 229, 0.4);
		z-index: 99;
		transition: all 0.3s ease;
	}

	.photo-fab:active {
		transform: scale(0.95);
		box-shadow: 0 4rpx 12rpx rgba(30, 136, 229, 0.6);
	}

	.fab-icon {
		font-size: 48rpx;
		color: $text-white;
	}

	.next-btn {
		position: fixed;
		bottom: 30rpx;
		left: 50%;
		transform: translateX(-50%);
		width: calc(100% - 60rpx);
		max-width: 660rpx;
		height: 88rpx;
		background: linear-gradient(135deg, $primary 0%, $primary-light 100%);
		color: $text-white;
		border: none;
		border-radius: $radius-xl;
		font-size: $font-lg;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: $shadow-lg;
		transition: all 0.3s ease;
		z-index: 10;
	}
</style>